package controllers

import (
	RR "crypto/rand"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"math/big"
	"strconv"
	"time"
	"tmp_report/models"
	_ "tmp_report/models"
)

type MainController struct {
	beego.Controller
}

// Index
func (c *MainController) Get() {
	c.Data["ctime"] = time.Now().Format("2006-01-02")
	username := c.GetSession("Username")
	c.Data["IsLogin"] = username
	fmt.Println(username)
	c.TplName = "tmp/tmp_report.html"
}

// 温度填报，接收post请求
func (c *MainController) Post() {
	c.TplName = "tmp/tmp_report.html"
	var Jsons Jsons
	TmpInfo := models.TmpInfo{}
	o := orm.NewOrm()                     // 获取orm
	data := c.Ctx.Input.RequestBody       // 获取前端传来的Json数据
	err := json.Unmarshal(data, &TmpInfo) // 结构化数据
	if err != nil {
		fmt.Println("json.Unmarshal is err:", err.Error())
	}
	var Temperatrue, _ = strconv.ParseFloat(TmpInfo.Temperature, 64)
	if Temperatrue >= 45.0 || Temperatrue <= 30.0 {
		Jsons.Status, Jsons.Msg = 0, "请输入正确温度信息"
		c.Data["json"] = Jsons
		c.ServeJSON()
		return
	}
	_, InsertErr := o.Insert(&TmpInfo) // 数据插入数据库
	if InsertErr != nil {
		beego.Warning("写入数据库失败:", InsertErr)
		return
	}
	// 封装返回数据
	Jsons.Status = 1
	Jsons.Msg = "发送成功"
	c.Data["json"] = Jsons
	c.ServeJSON()
}

func (c *MainController) TmpReportApi() {
	TmpInfo := models.TmpInfo{Value1: false, Value2: false, Value3: false, Value4: false, Value5: false, Value6: false,
		Value7: false, Value8: false, Value9: false}
	name := c.GetString("name")
	TmpInfo.Name = name
	Temperature := RangeRand()
	TmpInfo.Temperature = Temperature
	o := orm.NewOrm()
	if _, Err := o.Insert(&TmpInfo); Err == nil {
		c.Data["json"] = TmpInfo
		c.ServeJSON()
		return
	}
	c.Data["json"] = "Error"
	c.ServeJSON()
}

func RangeRand() string {
	var max int64 = 365
	var min int64 = 360
	result, _ := RR.Int(RR.Reader, big.NewInt(max-min))
	da := float32(min+result.Int64()) / 10
	data := fmt.Sprintf("%.1f", da)
	return data
}
